package top.lshaci.learning.netty.rpc.provider;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;
import top.lshaci.learning.netty.rpc.comsumer.ClientBootstrap;

/**
 * NettyRpcServerHander
 *
 * @author lshaci
 * @since 1.0.0
 */
@Slf4j
public class NettyRpcServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        log.debug("msg: {}", msg);
        // 客户端在调用服务器的api时，我们需要定义一个协议
        // 比如我们要求 每次发消息是都必须以某个字符串开头 HelloService#hello#你好
        String message = msg.toString();
        if (message.startsWith(ClientBootstrap.providerName)) {
            String result = new HelloServiceImpl().hello(message.substring(message.lastIndexOf("#") + 1));
            ctx.writeAndFlush(result);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
